package com.eascs.afterloan.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.eascs.admin.common.utils.ExcelParser;
import com.eascs.admin.common.utils.ExcelType;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.afterloan.service.BankCardService;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;

@RestController
@RequestMapping("/rbankCard")
public class BankCardRestController {
	@Autowired
	BankCardService bankCardService;
	@Autowired
	O2oLoanapplyService o2oLoanapplyService;
	@Autowired
	O2oLoanUserService o2oLoanUserService;
	private static Logger log = LoggerFactory.getLogger(BankCardRestController.class);
	
	/**
	 * @Title: detail
	 * @Description: 银行卡信息详情页面
	 * @author 张庆奇
	 * @param billCode
	 * @return
	 * @return BaseRestResult<String>
	 * @throws
	 * @date 2017年6月7日 上午9:55:23
	 */
	@RequestMapping("/detail")
	public BaseRestResult<String>  detail(String billCode) {
		O2oLoanapplyEntity loanapply = o2oLoanapplyService.fingByBillCode(billCode);
		O2oLoanUserEntity loanUser = o2oLoanapplyService.findLoanUserEntity(loanapply.getLoanapplyNo(), loanapply.getLoanId());
		ViewContext.put("loanapplyEntity", loanapply);
		ViewContext.put("loanUser", loanUser);
		return HtmlRestResult.popHtmlFragment("bankCard/detail"); 
	}

	/**
	 * @Title: exportInfo
	 * @Description: 弹出银行卡信息导入页面
	 * @author 张庆奇
	 * @return
	 * @return BaseRestResult<String>
	 * @throws
	 * @date 2017年6月7日 上午9:55:41
	 */
	@RequestMapping("/exportInfo")
	public BaseRestResult<String>  exportInfo() {
	
		return HtmlRestResult.popHtmlFragment("bankCard/exportInfo"); 
	}

	/**
	 * @Title: dowanload
	 * @Description: 下载导入银行卡信息模板
	 * @author 张庆奇
	 * @param httpServletResponse
	 * @param request
	 * @return
	 * @return BaseRestResult<String>
	 * @throws
	 * @date 2017年6月7日 上午9:55:58
	 */
	@RequestMapping("/download")
	public BaseRestResult<String> dowanload(HttpServletResponse httpServletResponse, HttpServletRequest request) {
		BaseRestResult<String> result = null;
		String file = BankCardRestController.class.getResource("/excelTemplate/bank_card_model.xls").getPath();

		OutputStream os = null;
		try {
			String outfile = "银行卡信息导入模板.xls";
			outfile=encodeChineseDownloadFileName(request,outfile);
			File f = new File(file);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
		return result;
	}
	
	/**
	 * 银行信息表导入 刷新
	 * @param file
	 * @param billCode
	 * @param loanerName
	 * @param idNum
	 * @return
	 */
	@RequestMapping("/uploadExecl")
	public BaseRestResult<String> uploadExcel(@RequestParam(value = "file", required = false) MultipartFile file, String billCode,String loanerName,String idNum) {
		@SuppressWarnings("unused")
		InputStream inputStream = null;
		try {
			inputStream = file.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		ExcelType[] types = new ExcelType[] {//验证excel数据是否正确
				new ExcelType(ExcelType.CELL_TYPE_STRING, true),//1
				new ExcelType(ExcelType.CELL_TYPE_STRING, true),//2
				new ExcelType(ExcelType.CELL_TYPE_STRING, true),//3
				new ExcelType(ExcelType.CELL_TYPE_STRING, true)//4

		};
		
		long beginTime = System.currentTimeMillis();
		ExcelParser parser = new ExcelParser(types);
		try {
			parser.run(file.getInputStream());
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		List<Object> errorresults = parser.getErrorresults();
		StringBuffer error = new StringBuffer();
		for (int i = 0; i < errorresults.size(); i++) { //如果数据格式有问题，先打出loger 
			
			error.append("导入数据有误请检查：错误数据位置为："+(String) errorresults.get(i)+"\r\n");
			log.error("error.excel.read", (String) errorresults.get(i));
		}
		if(error!=null&&StringUtils.isNotBlank(error)){
			return BaseRestResult.warn(error.toString());
		}
		List<List<Object>> results = parser.getResults();  //解析出来的数据
		//循环去查询表插入银行卡信息报表		
		log.info(new StringBuilder().append("耗时：").append(
				(System.currentTimeMillis() - beginTime)).append(
				",导入记录数：").append(results.size()).append(
				",批量导入级别-导入Excel").toString());
		String result = null;
		try {
			result = bankCardService.addList(results);
		} catch (RuntimeException e) {
			return BaseRestResult.info(e.getLocalizedMessage()).andRefresh();
		}
		if(result.equals("success")){
			log.info("银行卡信息导入数据插入临时表中成功。");
			return BaseRestResult.info("导入成功").andTopRedirect("/bankCard/bank_card_info");
			
		}else{
			log.info("银行卡信息导入数据插入临时表失败。");
			return BaseRestResult.info("导入失败").andRefresh();
		}
		
		
	}
	
    /** 
     * 对文件流输出下载的中文文件名进行编码 屏蔽各种浏览器版本的差异性 
     * @throws UnsupportedEncodingException  
     */  
    public static String encodeChineseDownloadFileName(  
            HttpServletRequest request, String pFileName) throws UnsupportedEncodingException {  
          
         String filename = null;    
            String agent = request.getHeader("USER-AGENT");    
            if (null != agent){    
                if (-1 != agent.indexOf("Firefox")) {//Firefox    
                    filename = "=?UTF-8?B?" + (new String(org.apache.commons.codec.binary.Base64.encodeBase64(pFileName.getBytes("UTF-8"))))+ "?=";    
                }else if (-1 != agent.indexOf("Chrome")) {//Chrome    
                    filename = new String(pFileName.getBytes(), "ISO8859-1");    
                } else {//IE7+    
                    filename = java.net.URLEncoder.encode(pFileName, "UTF-8");    
                    filename = StringUtils.replace(filename, "+", "%20");//替换空格    
                }    
            } else {    
                filename = pFileName;    
            }    
            return filename;   
    }  
	
	
}
